<template>
    <div class="layout-container">
        <!-- 侧边栏 -->
        <el-aside :width="isCollapsed ? '64px' : '200px'" class="sidebar">
            <div class="logo">
                <el-icon v-if="isCollapsed" size="24">
                    <Setting />
                </el-icon>
                <span v-else>管理系统</span>
            </div>

            <el-menu :default-active="activeMenu" class="sidebar-menu" :collapse="isCollapsed" :unique-opened="true"
                router background-color="#304156" text-color="#bfcbd9" active-text-color="#409EFF">
                <template v-for="menu in userMenus" :key="menu.id">
                    <el-menu-item v-if="!menu.children || menu.children.length === 0" :index="menu.path">
                        <el-icon>
                            <component :is="menu.icon" />
                        </el-icon>
                        <template #title>{{ menu.name }}</template>
                    </el-menu-item>

                    <el-sub-menu v-else :index="menu.path">
                        <template #title>
                            <el-icon>
                                <component :is="menu.icon" />
                            </el-icon>
                            <span>{{ menu.name }}</span>
                        </template>
                        <el-menu-item v-for="child in menu.children" :key="child.id" :index="child.path">
                            <el-icon>
                                <component :is="child.icon" />
                            </el-icon>
                            <template #title>{{ child.name }}</template>
                        </el-menu-item>
                    </el-sub-menu>
                </template>
            </el-menu>
        </el-aside>

        <!-- 主内容区 -->
        <el-container class="main-container">
            <!-- 顶部导航 -->
            <el-header class="header">
                <div class="header-left">
                    <el-button type="text" @click="toggleSidebar" class="collapse-btn">
                        <el-icon size="20">
                            <Expand v-if="isCollapsed" />
                            <Fold v-else />
                        </el-icon>
                    </el-button>

                    <el-breadcrumb separator="/" class="breadcrumb">
                        <el-breadcrumb-item v-for="item in breadcrumbs" :key="item.path">
                            {{ item.name }}
                        </el-breadcrumb-item>
                    </el-breadcrumb>
                </div>

                <div class="header-right">
                    <el-dropdown @command="handleUserCommand">
                        <span class="user-info">
                            <el-icon>
                                <User />
                            </el-icon>
                            {{ userInfo?.username }}
                            <el-icon class="el-icon--right">
                                <ArrowDown />
                            </el-icon>
                        </span>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                                <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </el-header>

            <!-- 主内容 -->
            <el-main class="main-content">
                <router-view />
            </el-main>
        </el-container>
    </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage, ElMessageBox } from 'element-plus'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

const isCollapsed = ref(false)

const userInfo = computed(() => authStore.userInfo)
const userMenus = computed(() => authStore.userMenus)
const activeMenu = computed(() => route.path)

// 面包屑导航
const breadcrumbs = computed(() => {
    const pathArray = route.path.split('/').filter(Boolean)
    const crumbs = [{ name: '首页', path: '/' }]

    let currentPath = ''
    pathArray.forEach(path => {
        currentPath += `/${path}`
        const menu = findMenuByPath(currentPath, userMenus.value)
        if (menu) {
            crumbs.push({ name: menu.name, path: currentPath })
        }
    })

    return crumbs.slice(1) // 移除首页，因为我们不在首页
})

// 查找菜单
function findMenuByPath(path, menus) {
    for (const menu of menus) {
        if (menu.path === path) {
            return menu
        }
        if (menu.children) {
            const found = findMenuByPath(path, menu.children)
            if (found) return found
        }
    }
    return null
}

// 切换侧边栏
const toggleSidebar = () => {
    isCollapsed.value = !isCollapsed.value
}

// 用户操作
const handleUserCommand = async (command) => {
    switch (command) {
        case 'profile':
            ElMessage.info('个人信息功能开发中...')
            break
        case 'logout':
            try {
                await ElMessageBox.confirm(
                    '确定要退出登录吗？',
                    '退出确认',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                )
                authStore.logout()
                router.push('/login')
                ElMessage.success('已退出登录')
            } catch {
                // 用户取消
            }
            break
    }
}

// 初始化认证状态
const initializeAuth = async () => {
    if (authStore.isAuthenticated && authStore.userMenus.length === 0) {
        try {
            await authStore.getCurrentUser()
        } catch (error) {
            console.error('初始化用户信息失败:', error)
        }
    }
}

onMounted(() => {
    initializeAuth()
})
</script>

<style scoped>
.layout-container {
    height: 100vh;
    display: flex;
}

.sidebar {
    background-color: #304156;
    transition: width 0.3s;
}

.logo {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 18px;
    font-weight: bold;
    border-bottom: 1px solid #434a50;
}

.sidebar-menu {
    border: none;
    height: calc(100vh - 60px);
    overflow-y: auto;
}

.main-container {
    flex: 1;
    background-color: #f0f2f5;
}

.header {
    background: white;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    border-bottom: 1px solid #e6e6e6;
    box-shadow: 0 1px 4px rgba(0, 21, 41, .08);
}

.header-left {
    display: flex;
    align-items: center;
}

.collapse-btn {
    margin-right: 20px;
    color: #666;
}

.breadcrumb {
    font-size: 14px;
}

.header-right {
    display: flex;
    align-items: center;
}

.user-info {
    display: flex;
    align-items: center;
    color: #666;
    cursor: pointer;
    padding: 8px 12px;
    border-radius: 4px;
    transition: background-color 0.3s;
}

.user-info:hover {
    background-color: #f5f5f5;
}

.main-content {
    padding: 20px;
    min-height: calc(100vh - 60px);
}
</style>